#!/bin/env python3
#coding:utf-8

import requests
import json
import sys
import psutil
import time


USER = "admin"
PASSWORD = "admin"
TEMPLATE_ID = 2
URL = "http://192.168.0.10:3000"

#CPU告警值
CPU_ALERT = 30.0

def runTask():
  url = "%s/api/auth/login"%(URL)

  payload = json.dumps({
    "auth": USER,
    "password": PASSWORD
  })
  headers = {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  }
  response = requests.request("POST", url, headers=headers, data=payload)

  if response.status_code != 204 :
    print("登录失败，请检查用户名和密码.... ")
  else:
    # print(response.cookies.get("semaphore"),type(response.cookies.get("semaphore")))
    # url = "http://192.168.0.103:3000/api/project/1/tasks"
    url = "%s/api/project/1/tasks"%(URL)

    payload = json.dumps({
      "template_id": TEMPLATE_ID
    })
    headers = {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'Cookie': "semaphore="+ response.cookies.get("semaphore")
    }
    response2 = requests.request("POST", url, headers=headers, data=payload)
    print(response2.text)

def getCpu() -> float:
  # 获取CPU使用率
  return psutil.cpu_percent(interval=1)

def main() -> int:
  try:
    while True:
      print("监控主机CPU状态")
      cpu = getCpu()
      if cpu >= CPU_ALERT :
        print("CPU使用率当前为:%s%%,告警值为:%s%%"%(cpu,CPU_ALERT),"触发扩容流程")
        runTask()
      else:
        print("CPU使用率当前为:%s%%,告警值为:%s%%"%(cpu,CPU_ALERT))
      time.sleep(5)
  except:
    return 1
 
  return 0

if __name__ == '__main__':
    sys.exit(main())
    # main()
